#pragma pack_matrix(row_major)

Texture2D baseTexture : register (t0);
Texture2D normalMap : register (t1);

SamplerState filters : register (s0);
struct vOutput {
	float4 wpos : POSITION;
	float3 normal : NORMAL;
	float2 uv : TEXCOORD;
	float3 tangent : TANGENT;
	float4 pos : SV_POSITION;
};

cbuffer OBJECT : register(b0){
	float4x4 mWorld;
}

cbuffer SCENE: register(b1){
	float4x4 mView;
	float4x4 mProj;
	float4 camPos;
}

cbuffer LIGHT : register(b2){
	float4 color;
	float4 lightPos;
}

float4 main(vOutput input) : SV_TARGET
{

	float intensity;
	float3x3 TBN = float3x3(
		normalize(input.tangent),
		normalize(cross(input.tangent.xyz,input.normal.xyz)),
		normalize(input.normal)
		);
	//TBN = transpose(TBN);
	//float3 normal = float3(0,1,0);
	float3 normal = normalMap.Sample(filters,input.uv).xyz * 2 - 1;

	float3 lightDir = normalize(lightPos.xyz - input.wpos);

	float3 lightDirTan = normalize(mul(lightDir,TBN));
		float lightRatio = saturate(dot(lightDirTan,normal));
	float attenuation = 1.0f - saturate(length(lightPos-input.wpos)/5);
	intensity = lightRatio * attenuation * color;


		float3 toCamera = normalize(camPos - input.wpos);
		float3 toCamTan = normalize(mul(toCamera,TBN));


	float3 reflected = reflect(-lightDirTan, normal);
		float specular = saturate(dot(reflected,toCamTan));
	specular = pow(specular,20);

	return intensity * (specular + baseTexture.Sample(filters,input.uv));

}